#coding=utf8
import socket

def gethostbyname(name):
    '''域名查ip'''
    try:
        return socket.gethostbyname(name)
    except socket.gaierror:
        return '0.0.0.0'

def gethostbyaddr(addr):
    ''''''
    try:
        return socket.gethostbyaddr(addr)[0]
    except socket.herror:
        return addr

class PathResult(BaseModel):
    """目录扫描结果"""
    #taskid       = sql.ForeignKeyField(ScanTask)
    uid          = sql.PrimaryKeyField()
    host         = sql.CharField()
    name         = sql.CharField()
    fid          = sql.IntegerField(default = 0)     #父目录id 0-为根目录
    isfolder     = sql.BooleanField(default = True)  #是否是文件夹
    #status       = sql.IntegerField(default = 200)

    #######################
    #pathdict = {} #路径缓存
    #flag     = 0  #

    @classmethod
    def list2dict(self,path):
        """
        路径list生成dict树状结构
        L = [1,2,3,4]
        转换成
        D = {1:{2:{3:{4:{}}}}}
        """
        folders = {}
        for folder in path[::-1]:
            if folder:folders = {folder:folders}
        return folders

    @classmethod
    def dict2tree(self,d1,d2):
        """
        dict树状结构合并
        dict1={1:{2:{3:{4:{}}}}}
        dict2={1:{2:{4:{6:{}}}}}
        dict3={1:{2:{3:{5:{}}}}}
        合并成
        dict4 = {1:{2:{3:{4:{}},5:{}},4:{6:{}}}}
        """
        if isinstance(d2,dict):
            k1 = d1.keys()
            for k in d2.keys():
                if k in k1:
                   return self.dict2tree(d1[k],d2[k])
                else:
                   return d1.update(d2)

    @classmethod
    def dict2db(self,host,value,fid=0):
        for k,v in value.items():
            p,c=self.get_or_create(host=host,name=k,fid=fid)
            if v:
                self.dict2db(host,v,fid=p.id)

    @classmethod
    def savepath(cls,f):
        def F(self,req):
            '''
            cls.flag += 1
            if cls.flag >= 10: #此处数值根据具体业务情况修改
                cls.dict2db(req.netloc,cls.pathdict)
                cls.flag = 0
                cls.pathdict = {}
            else:
                cls.dict2tree(cls.pathdict,cls.list2dict(req.path.split('/')))
            '''
            cls.dict2db(req.netloc,cls.list2dict(req.path.split('/')))
            return f(self,req)
        return F

if __name__ == '__main__':  
    print(gethostbyname('www.sddgds-assdasds-sdfdsf-sdf.com')) 